package top.laoliu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.laoliu.pojo.*;
import top.laoliu.service.*;
import top.laoliu.util.SmsUtils;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: acer
 * @Date: 2020/10/15 23:08
 * @Description:
 */
@Controller
@RequestMapping("/company")
public class CompanyController {
    @Autowired
    private CompanyService companyService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private DeliveryService deliveryService;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public String login(Company company, HttpSession session) {
        String email = company.getEmail();
        String password = company.getPassword();
        System.out.println(company);
        if (companyService.companyLogin(email, password)) {
            Company companyByEmail = companyService.getCompanyByEmail(email);
            System.out.println(companyByEmail);
            session.setAttribute("company", companyByEmail);
            session.setMaxInactiveInterval(60 * 60);
            System.out.println("公司用户登陆成功");
            return "true";
        }
        System.out.println("公司用户登录失败");
        return "false";
    }


    @RequestMapping("/toLoginPage")
    public String toLoginPage() {
        return "redirect:/user/toLoginPage";
    }

    @RequestMapping("/toRegisterPage")
    public String toRegisterPage() {
        return "redirect:/user/register";
    }

    @RequestMapping("/toCompanyProfile")
    public String toCompanyProfile(HttpSession session, Model model) {
        Company company = (Company)session.getAttribute("company");
        CompanyInfo companyInfo = companyService.getCompanyInfo(company.getCompany_id());
        System.out.println(companyInfo);
        model.addAttribute("companyInfo",companyInfo);
        return "companyProfile";
    }

    @RequestMapping("/logout")
    public String logout(Model model, HttpSession session) {
        model.addAttribute("company", session.getAttribute("company"));
        session.removeAttribute("company");
        System.out.println("退出成功");
        return "forward:toLoginPage";
    }

    @RequestMapping("/toChangePassword")
    public String toChangePassword() {
        return "companyChangePassword";
    }

    @RequestMapping("/toPostJob")
    public String toPostJob() {
        return "postJob";
    }

    @RequestMapping("/postJobData")
    @ResponseBody
    public String postJobData(Position position){
        position.setBrowsing_number(0);
        position.setStatus(1);
        System.out.println(position);
        int i = positionService.insertPosition(position);
        if (i>0){
            return "发布成功";
        }
        return "发布失败,请重试";
    }

    @RequestMapping("/toPostedJob")
    public String toPostedJob(Model model, HttpSession session) {
        Company company = (Company) session.getAttribute("company");
        Integer company_id = company.getCompany_id();
        List<Position> positions = positionService.getPositionsByCompany_id(company_id);
        model.addAttribute("positions", positions);
        return "postedJob";
    }

    @RequestMapping("/toApplyManage")
    public String toApplyManage(Model model, HttpSession session) {
        Company company = (Company) session.getAttribute("company");
        Integer company_id = company.getCompany_id();
        List<Position> positions = positionService.getPositionsByCompany_id(company_id);
        int size = positions.size();
        model.addAttribute("size", size);
        List<ApplyInfo> applyInfos = companyService.getApplyInfoByCompany_id(company_id);
        model.addAttribute("applyInfos", applyInfos);
        model.addAttribute("applyNumber", applyInfos.size());
        return "applyManage";
    }

    @RequestMapping("/approveApply/{position_id}/{user_id}")
    public String approveApply(@PathVariable Integer position_id, @PathVariable Integer user_id) {
        deliveryService.updateDeliveryStatus(new PositionResume(position_id, user_id, null, 2));
        return "redirect:/company/toApplyManage";
    }

    @RequestMapping("/rejectApply/{position_id}/{user_id}")
    public String rejectApply(@PathVariable Integer position_id, @PathVariable Integer user_id) {
        deliveryService.updateDeliveryStatus(new PositionResume(position_id, user_id, null, 0));
        return "redirect:/company/toApplyManage";
    }

    @RequestMapping("/showResume/{user_id}")
    public String showResume(@PathVariable Integer user_id, Model model) {
        ResumeVo resume = resumeService.getResumeVoByUserId(user_id);
        model.addAttribute("resume", resume);
        User userById = userService.getUserById(user_id);
        model.addAttribute("username",userById.getUsername());
        return "showResume";
    }

    @RequestMapping("/changePassword")
    @ResponseBody
    public String changePassword(String email, String oldPassword, String newPassword, String confirmPassword, HttpSession session) {
        System.out.println(email);
        System.out.println(oldPassword);
        System.out.println(newPassword);
        System.out.println(confirmPassword);
        boolean pwdIsTrue = companyService.companyLogin(email, oldPassword);
        if (!pwdIsTrue) {
            return "旧密码输入有误";
        } else {
            if (session.getAttribute("user") != null) {
                session.removeAttribute("user");
            }
            Company companyByEmail = companyService.getCompanyByEmail(email);
            companyByEmail.setPassword(newPassword);
            companyService.updateCompany(companyByEmail);
            return "修改成功，请返回登录页面重新登录";
        }
    }


    @RequestMapping("/register")
    @ResponseBody
    public String register(Company company, String messageCode, HttpSession session) {
        System.out.println("register" + company);
        System.out.println("register" + messageCode);
        System.out.println("register" + session.getAttribute("messageCode"));
        if (companyService.isExistCompany(company.getEmail(), company.getPhone())) {
            System.out.println("邮箱或手机号已被注册");
            return "邮箱或手机号已被注册";
        } else if (!messageCode.equalsIgnoreCase((String) session.getAttribute("messageCode"))) {
            System.out.println("验证吗21312312" + (String) session.getAttribute("messageCode"));
            System.out.println(messageCode.equalsIgnoreCase((String) session.getAttribute("messageCode")));
            System.out.println("验证码有误!");
            return "验证码有误!";
        } else if ("".equals(company.getName())) {
            return "请输入用户名";
        } else if ("".equals(company.getEmail())) {
            return "请输入邮箱";
        } else if ("".equals(company.getPhone())) {
            return "请输入电话号码";
        } else if ("".equals(company.getPassword())) {
            return "请输入密码";
        } else {
            companyService.insertCompany(company);
            System.out.println("注册成功");
            return "注册成功";
        }
    }


    @RequestMapping("/getMessageCode")
    @ResponseBody
    public void getMessageCode(String phone, HttpSession session) {
        System.out.println("phone" + phone);
        try {
            if (session.getAttribute("messageCode") == null) {
                String messageCode = SmsUtils.getPhoneMessageCode(phone);
//                String messageCode = "831680";
                if (messageCode != null) {
                    session.setAttribute("messageCode", messageCode);
                    session.setMaxInactiveInterval(60);
                    System.out.println(messageCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/saveCompanyInfo")
    @ResponseBody
    public String saveCompanyInfo(CompanyInfo companyInfo){

        System.out.println(companyInfo);
        if (companyService.getCompanyInfo(companyInfo.getInfo_id())==null){
            companyInfo.setLogo((int)(Math.random() * 13 + 1)+".jpg");
            int isSave = companyService.insertCompanyInfo(companyInfo);
            if (isSave>0){
                return "保存成功";
            }else {
                return "保存失败";
            }
        }else {
            int isUpdate = companyService.updateCompanyInfo(companyInfo);
            if (isUpdate>0){
                return "保存成功";
            }else {
                return "保存失败";
            }
        }
    }
}
